package ophiux.alipay.template.client;

import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

import ophiux.OphiuxAlipayTemplateMessageException;
import ophiux.alipay.template.base.Color;
import ophiux.alipay.template.base.Value;
import ophiux.alipay.template.request.BaseTemplate;
import ophiux.alipay.template.sign.AlipayHashMap;
import ophiux.alipay.template.sign.AlipaySignature;
import ophiux.alipay.template.sign.RequestParametersHolder;
import ophiux.alipay.util.HttpUtil;
import ophiux.alipay.util.StringUtil;

public class AlipayTemplateMessageParser implements IAlipayTemplateMessageParser {

	@Override
	public String toJson(BaseTemplate _request) throws OphiuxAlipayTemplateMessageException {
		String url = StringUtil.isEmpty(_request.getUrl())?"":_request.getUrl();
		String actionName = StringUtil.isEmpty(_request.getAction_name())?"":_request.getAction_name();
		String headColor = StringUtil.isEmpty(_request.getHead_color())?"":_request.getHead_color();
		
		if(StringUtil.isEmpty(_request.getTo_user_id())) {
			throw new OphiuxAlipayTemplateMessageException("fail","to_user_id is null");
		}
		if(StringUtil.isEmpty(_request.getTemplate_id())) {
			throw new OphiuxAlipayTemplateMessageException("fail","template_id is null");
		}
		
		String json="{\"to_user_id\":\""+_request.getTo_user_id()+"\",\"template\":{\"template_id\":\""+_request.getTemplate_id()+"\","
				+"\"context\":{\"headColor\":\""+headColor+"\",\"url\":\""+url+"\",\"actionName\":\""+actionName+"\",";
		Field[]  fieldList = _request.getClass().getFields();
		try {
			for (int i = 0; i < fieldList.length; i++) {
				Field field=fieldList[i];
				Value value = field.getAnnotation(Value.class);
				Color color = field.getAnnotation(Color.class);
				if(StringUtil.isEmpty(value.value())){
					throw new OphiuxAlipayTemplateMessageException("fail","@Value() is null");
				}
				json+="\""+value.value()+"\":{";
				if(!StringUtil.isEmpty(field.get(_request)+"")) {
					json+="\"value\":\""+field.get(_request)+"\",";
				}else {
					json+="\"value\":\"\",";
				}
				json+="\"color\":\""+(color.value()!=null?color.value():"")+"\"},";
			}
			json=json.substring(0,json.length()-1)+"}}}";
			System.out.println("返回json==="+json);
//			String result = send(json, _request);
			return json;
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
			throw new OphiuxAlipayTemplateMessageException(e);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
			throw new OphiuxAlipayTemplateMessageException(e);
		}
//		return json;
	}

	public String send(String json,BaseTemplate baseTemplate) throws OphiuxAlipayTemplateMessageException {
		RequestParametersHolder requestHolder = new RequestParametersHolder();

		AlipayHashMap protocalMustParams = new AlipayHashMap();
		protocalMustParams.put("app_id", baseTemplate.getApp_id());
		protocalMustParams.put("method","alipay.open.public.message.single.send");
		protocalMustParams.put("format", "JSON");
		protocalMustParams.put("charset", "UTF-8");
		protocalMustParams.put("sign_type", "RSA2");
		protocalMustParams.put("version", "1.0");
		Long timestamp = Long.valueOf(System.currentTimeMillis());
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		df.setTimeZone(TimeZone.getTimeZone("GMT+8"));
		protocalMustParams.put("timestamp",df.format(new Date(timestamp.longValue())));
		protocalMustParams.put("biz_content", json);

		requestHolder.setProtocalMustParams(protocalMustParams);
		String signContent = AlipaySignature.getSignatureContent(requestHolder);
		System.out.println("签名内容:" + signContent);
		try {
			String sign = AlipaySignature.rsaSign(signContent,baseTemplate.getPrivateKey(),"UTF-8", "RSA2");
			System.out.println("签名:" + sign);
			protocalMustParams.put("sign", sign);
			String param = AlipaySignature.buildQuery(protocalMustParams);
			System.out.println("访问参数:" + param);
//			param = URLEncoder.encode(param,"UTF-8");
			String result = HttpUtil.sendPost("https://openapi.alipaydev.com/gateway.do", param);
			System.out.println(result);
			
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			throw new OphiuxAlipayTemplateMessageException(e);
		}
	}
	
	 
}
